package com.jason.ladder.webapp.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.jason.ladder.Constants;
import com.jason.ladder.model.User;
import com.jason.ladder.service.UserExistsException;
import com.jason.ladder.service.UserManager;

@Controller
@RequestMapping("/content/signup")
public class SignUpController {
	@Autowired
	UserManager userManager;
	private static Logger logger = Logger.getLogger( SignUpController.class );
	
	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView showForm(HttpServletRequest request){
		ModelAndView mav = new ModelAndView("signUp");
		mav.addObject("user", new User());
		
		return mav;
	}
	
	@RequestMapping(method = RequestMethod.POST)
    public ModelAndView signUp( HttpServletRequest request ) throws IOException {
        ModelAndView mav = new ModelAndView();   
        System.out.println("In signUp method");
        logger.warn("In signUp method");
		User user = new User(request.getParameter("email"),request.getParameter("name"),request.getParameter("password"),request.getParameter("confirmPassword"));
		//do some validation
		Boolean error = false;
		if(!user.getEmail().contains("@")){
			error = true;
			logger.warn("email does not contain @");
			//errors.rejectValue("email", "errors.invalidEmail");
		}
		if(!(user.getName().length()>0)){
			error = true;
			logger.warn("name is not > 0");
			//errors.rejectValue("name", "errors.name.length");
		}
		if(!user.getPassword().equals(user.getConfirmPassword())){
			error = true;
			logger.warn("passwords do not match");
			//errors.rejectValue("password", "errors.passwordMatch");
		}
		if(!error){
			try {
				logger.warn("saving user");
				User user1 = userManager.save(user);
				request.getSession(true).setAttribute( Constants.SESSION_USER , user1);
				mav.setViewName("redirect:/content/ladder");
			} catch (UserExistsException e) {
				// TODO Auto-generated catch block
				logger.warn("user exists error");
				System.out.println(e.getMessage());
				//e.printStackTrace();
				mav.setViewName("login");
				mav.addObject("user", new User());
				mav.addObject("error", "Username is already in use.");
			}
			 
			
		}else{
			logger.warn("in last else");
			System.out.println("in last else");
			List errorMessages = new ArrayList();
			errorMessages.add("There were errors in your submission.");
			mav.addObject("user", new User());
			mav.setViewName("login2");
			
		}
		//save user
		logger.warn("done");
       return mav;
    }
}
